#include <stdio.h>

#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#define DELAY_1S   1000*1000
#define DELAY_2S   2*1000*1000

/** Task ID Variables **/
osThreadId_t hhm_id, hw_id;

static void *HelloWorldTask(const char *arg)
{
    (void)arg;

    uint8_t i = 0;
    char task_name[50] = {0};
    char *task_name_p =  task_name;
    /** Delay 1s **/
    usleep(DELAY_1S); 
    /** Get task ID **/
    hw_id = osThreadGetId();
    /** Get task name **/
    task_name_p = osThreadGetName(hw_id);
    printf("\r\nHelloWorldTask TaskID:%d\r\n", hw_id);
    printf("HelloWorldTask TaskName:%s\r\n", task_name_p);
    while (1) {
        i++;
        if(i == 10){
            /** Suspend the task **/
            osThreadSuspend(hhm_id);
        }

        if(i == 15){
            /** Resume the task **/
            osThreadResume(hhm_id);
        }

        if(i == 20){
            /** Terminate the task **/
            osThreadTerminate(hhm_id);
            i = 0;
        }
        usleep(DELAY_1S);
        printf("Hello World!\r\n");
    }

    return NULL;
}

static void HelloWorldTaskEntry(void)
{
    /** Task attributes **/
    osThreadAttr_t attr;

    attr.name = "HelloWorldTask";   // Name
    attr.attr_bits = 0U;            // Attribute bits
    attr.cb_mem = NULL;             // Task control block's initial memory address, given by the system by default
    attr.cb_size = 0U;              // Task control block's memory size
    attr.stack_mem = NULL;          // Task stack's initial memory address, given by the system by default
    attr.stack_size = 4096;         // Task stack's memory size
    attr.priority = 12;             // Task priority

    /** Create the task **/
    if (osThreadNew((osThreadFunc_t)HelloWorldTask, NULL, &attr) == NULL) {
        printf("[HelloWorldTaskEntry] Failed to create HelloWorldTask!\n");
    }
}

static void *HelloHMTask(const char *arg)
{
    (void)arg;

    char HHMTask_name[50] = {0};
    char *task_name_p =  HHMTask_name;
    
    usleep(DELAY_1S);
    
    hhm_id = osThreadGetId();
    
    task_name_p = osThreadGetName(hhm_id);
    printf("HelloHMTask TaskID:%d\r\n", hhm_id);
    printf("HelloHMTask TaskName:%s\r\n", task_name_p);
    while (1) {
        usleep(DELAY_2S);
        printf("Hello Harmony!\r\n");
    }

    return NULL;
}

static void HelloHMTaskEntry(void)
{
    osThreadAttr_t attr;

    attr.name = "HelloHMTask";  
    attr.attr_bits = 0U;        
    attr.cb_mem = NULL;         
    attr.cb_size = 0U;          
    attr.stack_mem = NULL;      
    attr.stack_size = 4096;     
    attr.priority = 11;         // Priority higher than the other

    if (osThreadNew((osThreadFunc_t)HelloHMTask, NULL, &attr) == NULL) {
        printf("[HelloHMTaskEntry] Failed to create HelloHMTask!\n");
    }
}

SYS_RUN(HelloHMTaskEntry);
SYS_RUN(HelloWorldTaskEntry);
